package com.baidu.springboot_10_simpledemo.controller;

import com.baidu.springboot_10_simpledemo.domain.Department;
import com.baidu.springboot_10_simpledemo.domain.Emp;
import com.baidu.springboot_10_simpledemo.domain.PageBean;
import com.baidu.springboot_10_simpledemo.service.DeptService;
import com.baidu.springboot_10_simpledemo.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.support.HttpRequestHandlerServlet;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class EmpController {
    @Autowired
    EmpService empService;
    @Autowired
    DeptService deptService;
    //分页查询+复杂查询
    @GetMapping("/emps")
    public String findAllEmp(PageBean<Emp> pageBean,Emp emp,Model model){

       if (pageBean.getCurrentPage()==null||"".equals(pageBean.getCurrentPage())){
           pageBean.setCurrentPage(1);
       }
       if (pageBean.getPageSize()==null||"".equals(pageBean.getPageSize())){
           pageBean.setPageSize(7);
       }
        PageBean<Emp> pb = empService.findAll(pageBean,emp);
        List<Department> depts = deptService.findAll();
        model.addAttribute("depts",depts);
        model.addAttribute("pb",pb);
        model.addAttribute("emp",emp);

        return "emp/list";
    }
    //来到添加员工页面
    @GetMapping("/emp")
    public String toAddPage(Model model){
        List<Department> departments = deptService.findAll();
        model.addAttribute("depts",departments);
        return "emp/add";
    }
    //添加员工
    @PostMapping("/emp")
    public String addEmp(Emp emp){
        empService.addEmp(emp);
        return "redirect:/emps";
    }
    //来到修改页面（添加页面），add.html是一个二合一页面
    @GetMapping("/emp/{id}")
    public String toUpdatePage(@PathVariable("id")Integer id,Model model){
        List<Department> departments = deptService.findAll();
        model.addAttribute("depts",departments);
        Emp emp = empService.findById(id);
        model.addAttribute("emp",emp);
        return "emp/add";
    }
    //修改用户
    @PutMapping("/emp")
    public String updateEmp(Emp emp){
        empService.updateEmp(emp);
        return "redirect:/emps";
    }
    //删除用户
    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id")Integer id){
        empService.deleteEmp(id);
        return "redirect:/emps";
    }
    //删除选中
    @DeleteMapping("/emps")
    public  String delSelected(HttpServletRequest request){
        //获取被选中的所有员工id
        String[] eids = request.getParameterValues("eid");
        System.out.println(eids);
        empService.delSelected(eids);
        return  "redirect:/emps";
    }
}
